package com.vehiclesecure.config;

import com.vehiclesecure.model.EmergencyAlert;
import com.vehiclesecure.model.MaintenanceRecord;
import com.vehiclesecure.model.User;
import com.vehiclesecure.model.Vehicle;
import com.vehiclesecure.model.VehicleData;
import com.vehiclesecure.repository.EmergencyAlertRepository;
import com.vehiclesecure.repository.MaintenanceRecordRepository;
import com.vehiclesecure.repository.UserRepository;
import com.vehiclesecure.repository.VehicleDataRepository;
import com.vehiclesecure.repository.VehicleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 数据初始化器，用于在应用启动时插入示例数据到MongoDB数据库
 */
@Component
public class DataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;
    private final VehicleDataRepository vehicleDataRepository;
    private final EmergencyAlertRepository emergencyAlertRepository;
    private final MaintenanceRecordRepository maintenanceRecordRepository;
    private final PasswordEncoder passwordEncoder;
    private final VehicleRepository vehicleRepository;

    @Autowired
    public DataInitializer(UserRepository userRepository,
                          VehicleDataRepository vehicleDataRepository,
                          EmergencyAlertRepository emergencyAlertRepository,
                          MaintenanceRecordRepository maintenanceRecordRepository,
                          PasswordEncoder passwordEncoder,
                          VehicleRepository vehicleRepository) {
        this.userRepository = userRepository;
        this.vehicleDataRepository = vehicleDataRepository;
        this.emergencyAlertRepository = emergencyAlertRepository;
        this.maintenanceRecordRepository = maintenanceRecordRepository;
        this.passwordEncoder = passwordEncoder;
        this.vehicleRepository = vehicleRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        // 初始化用户数据
        initializeUsers();
        // 初始化车辆数据
        initializeVehicleData();
        // 初始化警报数据
        initializeEmergencyAlerts();
        // 初始化维修记录数据
        initializeMaintenanceRecords();
    }

    private void initializeUsers() {
        // 检查是否已有用户数据
        if (userRepository.count() == 0) {
            // 创建管理员用户
            User adminUser = User.builder()
                    .email("admin@vehiclesecure.com")
                    .password(passwordEncoder.encode("admin123"))
                    .firstName("Admin")
                    .lastName("User")
                    .role(User.Role.ADMIN)
                    .allowedVendors(List.of("Toyota", "Honda", "Ford"))
                    .build();

            // 创建普通用户
            User regularUser = User.builder()
                    .email("user@vehiclesecure.com")
                    .password(passwordEncoder.encode("user123"))
                    .firstName("Regular")
                    .lastName("User")
                    .role(User.Role.USER)
                    .allowedVendors(List.of("Toyota"))
                    .build();

            // 保存用户
            userRepository.saveAll(List.of(adminUser, regularUser));
            System.out.println("初始化用户数据完成");
        }
    }

    private void initializeVehicleData() {
        // 检查是否已有车辆数据
        if (vehicleDataRepository.count() == 0) {
            // 获取实际存在的车辆ID列表
            List<String> existingVehicleIds = vehicleRepository.findAll().stream()
                    .map(Vehicle::getId)
                    .collect(Collectors.toList());
            
            // 如果没有车辆，创建一些示例车辆
            if (existingVehicleIds.isEmpty()) {
                existingVehicleIds = createSampleVehicles();
            }
            
            List<VehicleData> vehicleDataList = new ArrayList<>();
            Random random = new Random();
            LocalDateTime now = LocalDateTime.now();

            // 为每辆车生成过去24小时的数据
            for (String vehicleId : existingVehicleIds) {
                String platePrefix = "京A";
                if (vehicleId.contains("2")) {
                    platePrefix = "沪B";
                } else if (vehicleId.contains("3")) {
                    platePrefix = "粤C";
                }
                String vehiclePlate = platePrefix + String.format("%05d", random.nextInt(100000));
                
                // 每辆车生成24小时的数据，每小时一条
                for (int i = 23; i >= 0; i--) {
                    LocalDateTime timestamp = now.minusHours(i);
                    
                    VehicleData data = new VehicleData();
                    data.setVehicleId(vehicleId);
                    data.setVehiclePlate(vehiclePlate);
                    data.setLatitude(39.9042 + (random.nextDouble() - 0.5) * 0.2);  // 北京附近随机经纬度
                    data.setLongitude(116.4074 + (random.nextDouble() - 0.5) * 0.2);
                    data.setSpeed(i % 3 == 0 ? random.nextInt(60) + 40 : random.nextInt(120));  // 随机速度
                    data.setEngineStatus(random.nextBoolean() ? 1 : 0);  // 随机引擎状态
                    data.setDoorLockStatus(random.nextBoolean() ? 1 : 0);  // 随机门锁状态
                    data.setFuelLevel(100 - (i * 4) + random.nextInt(5));  // 燃油量随时间减少
                    data.setEmergencyFlag(i % 12 == 0);  // 每12小时一个紧急情况
                    data.setTimestamp(timestamp);
                    
                    // 加密敏感数据会在VehicleDataService中处理
                    vehicleDataList.add(data);
                }
            }

            // 保存车辆数据
            vehicleDataRepository.saveAll(vehicleDataList);
            System.out.println("初始化车辆数据完成");
        }
    }
    
    private List<String> createSampleVehicles() {
        List<String> vehicleIds = new ArrayList<>();
        
        // 创建3辆示例车辆
        for (int i = 1; i <= 3; i++) {
            Vehicle vehicle = new Vehicle();
            vehicle.setId("vehicle-" + i);
            vehicle.setVin("VIN" + UUID.randomUUID().toString().substring(0, 10).toUpperCase());
            vehicle.setLicensePlate("测试" + String.format("%04d", i));
            vehicle.setBrand("品牌" + i);
            vehicle.setModel("型号" + i);
            vehicle.setStatus("ACTIVE");
            vehicle.setIsActive(true);
            vehicle.setCreatedAt(LocalDateTime.now());
            vehicle.setUpdatedAt(LocalDateTime.now());
            
            Vehicle savedVehicle = vehicleRepository.save(vehicle);
            vehicleIds.add(savedVehicle.getId());
        }
        
        System.out.println("创建了示例车辆: " + vehicleIds);
        return vehicleIds;
    }

    private void initializeEmergencyAlerts() {
        // 检查是否已有警报数据
        if (emergencyAlertRepository.count() == 0) {
            // 获取实际存在的车辆ID列表
            List<String> existingVehicleIds = vehicleRepository.findAll().stream()
                    .map(Vehicle::getId)
                    .collect(Collectors.toList());
            
            // 如果没有车辆，使用默认ID
            if (existingVehicleIds.isEmpty()) {
                existingVehicleIds = List.of("vehicle-1", "vehicle-2", "vehicle-3");
            }
            
            List<EmergencyAlert> alerts = new ArrayList<>();
            Random random = new Random();
            LocalDateTime now = LocalDateTime.now();

            // 创建几种不同类型的警报
            String[] alertTypes = {"THEFT_ATTEMPT", "ENGINE_OVERHEAT", "BATTERY_LOW", "DOOR_OPEN", "COLLISION_DETECTED"};
            
            for (int i = 0; i < 10; i++) {
                String vehicleId = existingVehicleIds.get(random.nextInt(existingVehicleIds.size()));
                String alertType = alertTypes[random.nextInt(alertTypes.length)];
                LocalDateTime createdAt = now.minusHours(random.nextInt(72));
                
                EmergencyAlert alert = new EmergencyAlert();
                alert.setVehicleId(vehicleId);
                alert.setVehiclePlate("测试车牌" + String.format("%05d", random.nextInt(100000)));
                alert.setAlertType(alertType);
                alert.setLatitude(39.9042 + (random.nextDouble() - 0.5) * 0.2);
                alert.setLongitude(116.4074 + (random.nextDouble() - 0.5) * 0.2);
                
                // 根据警报类型设置描述
                String description = switch (alertType) {
                    case "THEFT_ATTEMPT" -> "检测到车辆盗窃企图，请立即检查";
                    case "ENGINE_OVERHEAT" -> "发动机温度过高，建议立即停车检查";
                    case "BATTERY_LOW" -> "车辆电池电量过低，可能影响启动";
                    case "DOOR_OPEN" -> "检测到车门未关闭，请确认";
                    case "COLLISION_DETECTED" -> "检测到碰撞，可能发生事故";
                    default -> "未知警报类型";
                };
                alert.setDescription(description);
                
                // 随机设置警报状态，一半为活动状态
                boolean isActive = random.nextBoolean();
                alert.setStatus(isActive ? EmergencyAlert.AlertStatus.ACTIVE : EmergencyAlert.AlertStatus.RESOLVED);
                alert.setCreatedAt(createdAt);
                alert.setCreatedBy("SYSTEM");
                
                // 如果不是活动状态，则设置解决时间和解决者
                if (!isActive) {
                    alert.setResolvedAt(createdAt.plusMinutes(random.nextInt(120) + 30));
                    alert.setResolvedBy("系统管理员");
                }
                
                alerts.add(alert);
            }

            // 保存警报数据
            emergencyAlertRepository.saveAll(alerts);
            System.out.println("初始化警报数据完成");
        }
    }

    private void initializeMaintenanceRecords() {
        System.out.println("开始初始化维修记录数据...");
        System.out.println("当前维修记录数量: " + maintenanceRecordRepository.count());
        
        // 清除现有维修记录以确保重新创建
        maintenanceRecordRepository.deleteAll();
        System.out.println("清除现有维修记录后数量: " + maintenanceRecordRepository.count());
        
        // 获取用户ID
        User regularUser = userRepository.findByEmail("user@vehiclesecure.com").orElse(null);
        User adminUser = userRepository.findByEmail("admin@vehiclesecure.com").orElse(null);
        
        if (regularUser == null || adminUser == null) {
            System.out.println("用户不存在，跳过维修记录初始化");
            return;
        }
        
        // 获取实际存在的车辆ID列表
        List<String> existingVehicleIds = vehicleRepository.findAll().stream()
                .map(Vehicle::getId)
                .collect(Collectors.toList());
        
        // 如果没有车辆，使用默认ID
        if (existingVehicleIds.isEmpty()) {
            existingVehicleIds = List.of("vehicle-1", "vehicle-2", "vehicle-3");
        }
        
        List<MaintenanceRecord> records = new ArrayList<>();
        Random random = new Random();
        LocalDateTime now = LocalDateTime.now();

        String[] maintenanceTypes = {"REPAIR", "EMERGENCY_REPAIR", "REGULAR_MAINTENANCE", "ABNORMAL_HANDLING", "REPAIR", "EMERGENCY_REPAIR"};
        String[] descriptions = {
            "发动机异响，需要检查",
            "刹车系统故障，制动距离变长",
            "轮胎磨损严重，需要更换",
            "电池老化，启动困难",
            "需要定期保养更换机油",
            "变速箱换挡不顺畅"
        };
        
        for (int i = 0; i < 8; i++) {
            String vehicleId = existingVehicleIds.get(random.nextInt(existingVehicleIds.size()));
            String maintenanceType = maintenanceTypes[random.nextInt(maintenanceTypes.length)];
            LocalDateTime createdAt = now.minusHours(random.nextInt(168)); // 过去一周内的记录
            
            MaintenanceRecord record = new MaintenanceRecord();
            record.setVehicleId(vehicleId);
            record.setVehiclePlate("测试车牌" + String.format("%05d", random.nextInt(100000)));
            record.setMaintenanceType(maintenanceType);
            record.setDescription(descriptions[random.nextInt(descriptions.length)]);
            record.setStatus(MaintenanceRecord.MaintenanceStatus.PENDING);
            record.setPriority(random.nextBoolean() ? "HIGH" : "MEDIUM");
            record.setReportedAt(createdAt);
            record.setReportedBy(regularUser.getId());
            record.setReportedByName(regularUser.getFirstName() + " " + regularUser.getLastName());
            
            // 随机分配一些记录给服务商
            if (random.nextBoolean()) {
                record.setServiceProviderId("service-provider@vehiclesecure.com");
                record.setServiceProviderName("测试服务商");
                record.setStatus(MaintenanceRecord.MaintenanceStatus.IN_PROGRESS);
                record.setAssignedAt(createdAt.plusMinutes(random.nextInt(60) + 30));
            }
            
            records.add(record);
        }

        List<MaintenanceRecord> savedRecords = maintenanceRecordRepository.saveAll(records);
        System.out.println("成功保存维修记录数量: " + savedRecords.size());
        System.out.println("初始化维修记录数据完成");
    }
}